/**
 * CmdReceiver.java
 * 版权所有(C) 2013
 * 创建者:cuiran 2013-12-4 下午1:34:43
 */
package com.ghyf.mplay.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;

import com.ghyf.mplay.application.BaseCookie;
import com.ghyf.mplay.application.CookieConstants;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.bean.BaseModuleInfo;
import com.ghyf.mplay.bean.CountDownInfo;
import com.ghyf.mplay.bean.DateInfo;
import com.ghyf.mplay.bean.PicShowInfo;
import com.ghyf.mplay.bean.ScrollInfo;
import com.ghyf.mplay.bean.TextInfo;
import com.ghyf.mplay.bean.TimeInfo;
import com.ghyf.mplay.net.common.GData;
import com.ghyf.mplay.net.common.RecvBase;
import com.ghyf.mplay.net.data.ConfigFtpData;
import com.ghyf.mplay.net.data.ModuleTextBase;
import com.ghyf.mplay.net.data.ModuleTextData;
import com.ghyf.mplay.net.data.PriorityTextData;
import com.ghyf.mplay.net.ftp.FtpUpload;
import com.ghyf.mplay.net.log.LogTool;
import com.ghyf.mplay.net.serial.SerialTool;
import com.ghyf.mplay.util.CommonUtil;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.value.ConstantValue;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 接收控制中心发送的指令并进行处理<br>
 * 描述：当应用收到由控制中心发出的指令后，会在系统内发出广播，app应用对广播接收并进行处理。
 * @author cuiran
 * @version 1.0.0
 */
public class CmdReceiver extends BroadcastReceiver {
	private static final String TAG="CmdReceiver";
	private  Handler mHandler=new Handler();
	PowerManager pm=null;
	/* (non-Javadoc)
	 * @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		
		LogUtil.i(TAG, "接收广播");
		short cmdId=intent.getShortExtra(ConstantValue.EXTRA_TYPE , (short)0);
		short gId=intent.getShortExtra(ConstantValue.EXTRA_ID , (short)0);
		
		switch(cmdId){
		case RecvBase.CMD_CONTROL_GROUPSHOW://显示指定的组
		case RecvBase.CMD_CONTROL_GROUPHIDE://隐藏指定的组
			boolean isShow=cmdId==RecvBase.CMD_CONTROL_GROUPSHOW?true:false;
			
			BaseModuleInfo moduleInfo0= BaseCookie.moduleMap.get(gId);
			if(null!=moduleInfo0){
				if (moduleInfo0 instanceof ScrollInfo) {
					
					ScrollInfo scrollInfo = (ScrollInfo) moduleInfo0;
					scrollInfo.setVisibility(isShow);
					
				}else if(moduleInfo0 instanceof TextInfo){
			
					TextInfo textInfo= (TextInfo) moduleInfo0;
					textInfo.setVisibility(isShow);
				
				}else if(moduleInfo0 instanceof CountDownInfo){
					
					CountDownInfo downInfo=(CountDownInfo)moduleInfo0;
					downInfo.setVisibility(isShow);
					
				}else if(moduleInfo0 instanceof DateInfo){
					
					DateInfo dateInfo=(DateInfo)moduleInfo0;
					dateInfo.setVisibility(isShow);
					
				}else if(moduleInfo0 instanceof PicShowInfo){
					
					PicShowInfo picShowInfo=(PicShowInfo)moduleInfo0;
					picShowInfo.setVisibility(isShow);
					
				}else if(moduleInfo0 instanceof TimeInfo){
					
					TimeInfo timeInfo=(TimeInfo)moduleInfo0;
					timeInfo.setVisibility(isShow);
					
				}
				
			}
			break;
		
		case RecvBase.CMD_CONTROL_STARTEMERGENCY:
			
			
			break;
		case RecvBase.CMD_CONTROL_STOPEMERGENCY:
			
			
			break;
		case RecvBase.CMD_CONTROL_POWERON:
//			powerOn(context);
			powerControl("on");
			break;
		case RecvBase.CMD_CONTROL_POWEROFF:
//			powerOff(context);
			powerControl("off");
			break;
		case RecvBase.CMD_CONTROL_RESET:
			
			CommonUtil.reboot();
			break;
		case RecvBase.CMD_CONTROL_RESTARTSOFTWARE:
			sendCmd(context, ConstantValue.RESOFTWARE_RECEIVER);
			break;
		case RecvBase.CMD_FILE_SETCONFIG:
			try{
				ConfigFtpData ftpData0=(ConfigFtpData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				LogUtil.i(TAG, ftpData0.toString());
				
				
				LogUtil.i(TAG, ftpData0.getConfigFilename()+"-"+ftpData0.getSoftwareFilename()+"-"+ftpData0.getIp()+"-"+ftpData0.getPort()+"-"+ftpData0.getUsername()+"-"+ftpData0.getPassword());
			
				FtpUpload upload0=new FtpUpload(context,mHandler);
				ftpData0.setCmdId(cmdId);
				LogTool.addRunlog("配置更改","软件和配置发生改变，下载新版软件和配置！");
				if(null==ftpData0.getIp()||"".equals(ftpData0.getIp())){
					ftpData0.setIp(GData.FTP_HOST);
					ftpData0.setPort(21);
					ftpData0.setUsername("ftptest");
					ftpData0.setPassword("ftptest");
				}
			
				upload0.downloadFile(ftpData0);
				
			}catch (Exception e) {
				
				LogUtil.e(TAG, "CMD_FILE_SETCONFIG error", e);
			}
			break;
		case RecvBase.CMD_FILE_SETLIST:
			try{
				UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownload, true);
				UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownloadFail, false);
					
				ConfigFtpData ftpData1=(ConfigFtpData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				ftpData1.setCmdId(cmdId);
				LogUtil.i(TAG, ftpData1.getListMode()+",,"+ftpData1.getListFilename());
				LogTool.addRunlog("配置更改","下载播表");
				FtpUpload upload1=new FtpUpload(context,mHandler);
				if(null==ftpData1.getIp()||"".equals(ftpData1.getIp())){
					ftpData1.setIp(GData.FTP_HOST);
					ftpData1.setPort(21);
					ftpData1.setUsername("ftptest");
					ftpData1.setPassword("ftptest");
					
				}
			
				upload1.downloadFile(ftpData1);
			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_FILE_SETLIST error", e);
			}
			
			
			break;
		case RecvBase.CMD_FILE_GETLOG:
			try{
				FtpUpload upload=new FtpUpload(context,mHandler);
				
				ConfigFtpData ftpData=(ConfigFtpData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				LogUtil.i(TAG, ftpData.getIp()+"-"+ftpData.getPort()+"-"+ftpData.getUsername()+"-"+ftpData.getPassword());
				if(null==ftpData.getIp()||"".equals(ftpData.getIp())){
					ftpData.setIp(GData.FTP_HOST);
					ftpData.setPort(21);
					ftpData.setUsername("ftptest");
					ftpData.setPassword("ftptest");
				}
			
				upload.uploadFile(ftpData,ConstantValue.LOG_DIR);
			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_FILE_GETLOG error", e);
			}
			break;
			
		case RecvBase.CMD_TEXT_SETPROIRITY:
			try{
				PriorityTextData data=(PriorityTextData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				
				Message msg=new Message();
				msg.what=RecvBase.CMD_TEXT_SETPROIRITY;
				Bundle bundle=new Bundle();
				bundle.putSerializable(ConstantValue.EXTRA_OBJ, data);
				msg.setData(bundle);
				//TODO 需要发送 还未处理
//				if(BaseCookie.serviceHandler!=null){
//					BaseCookie.serviceHandler.handleMessage(msg);
//				}
			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_TEXT_SETPROIRITY error", e);
			}
			break;
			
		case RecvBase.CMD_TEXT_SETNORMAL:
			try{
				ModuleTextBase textBase=(ModuleTextBase)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				List<ModuleTextData> list=textBase.getModulelist();
				LogUtil.i(TAG, "接收实时文本消息数目："+list.size());
				Iterator<ModuleTextData> it=list.iterator();
				while(it.hasNext()){
					ModuleTextData data=it.next();
					int uid=data.getUid();
					String content=data.getContent().trim();
					LogUtil.i(TAG, "接收："+uid+" 内容："+content);
				
				
					BaseModuleInfo moduleInfo= BaseCookie.moduleMap.get(uid);
					 if (moduleInfo instanceof ScrollInfo) {
						ScrollInfo scrollInfo = (ScrollInfo) moduleInfo;
						ArrayList<String> temp_list=new ArrayList<String>();
						temp_list.add(data.getContent());
						scrollInfo.getmScroll().setTemp_list(temp_list);
						scrollInfo.getmScroll().setReceive(true);
						scrollInfo.getmScroll().stopThread();
						scrollInfo.getmScroll().startThread();
					}else if(moduleInfo instanceof TextInfo){
				
						TextInfo textInfo= (TextInfo) moduleInfo;
						textInfo.getmText().setText(content);
						
					}else if(moduleInfo instanceof CountDownInfo){
						CountDownInfo downInfo=(CountDownInfo)moduleInfo;
						int time=Integer.parseInt(content);
						downInfo.getmCountDown().setTime_countdown(time*1000);
					}
					
				}

			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_TEXT_SETNORMAL error", e);
			}
			break;
		case RecvBase.CMD_TEXT_STOP:
			try{
				ModuleTextData data1=(ModuleTextData)intent.getSerializableExtra(ConstantValue.EXTRA_OBJ);
				LogUtil.i(TAG, data1.getContent());
				Message msg1=new Message();
				msg1.what=cmdId;
				Bundle bundle1=new Bundle();
				bundle1.putSerializable(ConstantValue.EXTRA_OBJ, data1);
				msg1.setData(bundle1);
				//TODO 需要发送 还未处理
//				if(BaseCookie.serviceHandler!=null){
//					BaseCookie.serviceHandler.handleMessage(msg1);
//				}

				
			
			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_TEXT_STOP error", e);
			}
			break;
		case  RecvBase.CMD_SERIAL_REQUEST:
			try{
				Bundle bundle=	intent.getBundleExtra(ConstantValue.EXTRA_BUNDLE);
				if(bundle==null)return;
				byte commNum=bundle.getByte(ConstantValue.EXTRA_ID);
				byte[] data=bundle.getByteArray(ConstantValue.EXTRA_BYTES);
				
				SerialTool serialTool=new SerialTool();
				serialTool.openSeria("/dev/ttymxc"+commNum);
				serialTool.writeSeria(data);
				
//				byte b1=(byte)0xab;
//				byte b2=(byte)0xff;
//				byte b3=(byte)0x01;//0x01  0x02  0x03
//				byte b4=(byte)(b1+b2+b3);
//				byte[] data=new byte[4];
//				data[0]=b1;
//				data[1]=b2;
//				data[2]=b3;
//				data[3]=b4;
				
			
			}catch (Exception e) {
				LogUtil.e(TAG, "CMD_SERIAL_REQUEST error", e);
			}
		
			break;
		}
		
		
	}
	/**
	 * 开关机 
	 * 2014-12-4 下午3:33:01
	 * @param data on 或者off
	 *
	 */
	private void powerControl(String data){
		try{
			File file=new File(ConstantValue.SCREEN_PATH);
			if(file.exists()){
				FileOutputStream out=new FileOutputStream(file);
				out.write(data.getBytes());
				out.close();
			}
		}catch(Exception e){
			LogUtil.e(TAG,"powerControl error", e);
		}
	}
	/**
	 * 调用api-->暂时不用
	 * 2014-12-4 下午3:23:25
	 * @param context
	 *
	 */
	private void powerOn(Context context){
		try{
			UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsPowerOff, false);
			if(pm==null){
				 pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
			}
//			pm.setScreenStateLocked(true);
		}catch(Exception e){
			LogUtil.e(TAG, e);
		}
		
		
	}
	/**
	 * 调用api-->暂时不用
	 * 2014-12-4 下午3:23:25
	 * @param context
	 *
	 */
	private void powerOff(Context context){
		try{
			UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsPowerOff, true);
			 pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
//			 pm.setScreenStateLocked(false);
		}catch(Exception e){
			LogUtil.e(TAG, e);
		}
	}
	public void sendCmd(Context context,String action){
		  Intent myIntent = new Intent(action);  
		  myIntent.putExtra("path", ConstantValue.COMMAND_INSTALL_APP);
		  myIntent.setAction(action);  
		  context.sendBroadcast(myIntent);  
	}

	
}
